<template>
  <div class="login">
    <van-nav-bar
        title="用户注册"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />
    <div class="body">
    <van-form validate-first @submit="reg">
      <!-- 通过 pattern 进行正则校验 -->
      <van-field
          v-model="form.username"
          label="用户名"
          name="userName"
          placeholder="请输入用户名"
          :rules="[{ required: true,
                     message: '用户名不能为空'
                     },
                     {
                       pattern:/^([a-zA-Z0-9_-]|[\u4E00-\u9FA5]){4,9}$/,
                       message: '用户名长度4至9位数'
                     }
                     ]"
      />
      <van-field
          v-model="form.pwd"
          type="password"
          label="密码"
          name="pwd"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '密码不能为空' },{
            pattern:/[a-zA-Z0-9]{6,12}/,
            message: '密码格式不对'
          }]"
      />
      <van-field
          v-model="form.pwd2"
          type="password"
          label="重复密码"
          name="pwd2"
          placeholder="请再次输入密码"
          :rules="[{ required: true, message: '密码不能为空' },{
            validator,message: '两次密码输入不相同'
          },{
              pattern:/[a-zA-Z0-9]{6,12}/,
            message: '密码格式不对'
          }
          ]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">注&nbsp;&nbsp;&nbsp;&nbsp;册</van-button>
      </div>
    </van-form>
    </div>
  </div>
</template>

<script>
import {mapActions} from "vuex"
export default {

  name: "reg",
  data() {
    return {
      form:{
        username: '',
        pwd: '',
        pwd2: '',
      }


    };
  },
  methods: {
    onClickLeft() {
      this.$router.push('/login')
    },
    validator(val) {
      return   this.form.pwd===val


    },

    ...mapActions(["vreg","vlogin"]),
    reg(){
      this.vreg(this.form).then(()=>{
        this.$notify({type: 'success', message: '恭喜！注册成功'});
        this.vlogin(this.form).then(()=>{
          this.$router.push('/')
        })
      }).catch(err=>{
        this.$notify({type: 'danger', message: '注册失败'});
      });


    }
  },
}
</script>

<style lang="scss">
@import "public/sass/login";
</style>